package cn.itsource.org.controller;

import cn.itsource.basic.PageList;
import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.org.domain.Department;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//@GetMapping//获取数据
//@PostMapping//分页高级查询
//@PutMapping//新增或修改数据
//@DeleteMapping//删除数据

/*
写接口三要素：1.url是什么?2.参数是什么?3.返回值是什么?
 */
@RestController
@RequestMapping("/dept")
@Api(value = "部门的API",description="部门相关的CRUD功能")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;
    //添加或者修改
    @PutMapping
    @ApiOperation(value = "添加或者修改" )
    private AjaxResult addOrUpdate(@RequestBody Department department){

        try {
            if (department.getId()!=null){
                departmentService.update(department);
            }else {
                departmentService.add(department);
            }
            return  AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
//            ajaxResult.setSuccess(false);
//            ajaxResult.setMessage("操作失败！");
            //链式编程优化上面两行代码
            return AjaxResult.me().setSuccess(false).setMessage("操作失败！");
        }
    }
    //查询一个
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询" )
    private Department queryOne(@PathVariable("id") Long id){
        System.out.println(id);
        return departmentService.queryById(id);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "通过ID删除" )
    private AjaxResult remove(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
//            ajaxResult.setSuccess(false);
//            ajaxResult.setMessage("操作失败！");
            //链式编程优化上面两行代码
            return AjaxResult.me().setSuccess(false).setMessage("操作失败！");
        }
    }
    @PostMapping
    @ApiOperation(value = "分页查询" )
    private PageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){

        return departmentService.queryPage(departmentQuery);
    }

    @PatchMapping
    public AjaxResult batchRemove(@RequestBody List<Long> ids){
        try {
            System.out.println(111111);
            System.out.println(ids);
            departmentService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
//            ajaxResult.setSuccess(false)
//            ajaxResult.setMessage("操作失败！");
            //链式编程优化上面两行代码
            return AjaxResult.me().setSuccess(false).setMessage("操作失败！");
        }
    }

    @GetMapping
    public List<Department> queryTree(){
        return departmentService.queryTree();
    }
}
